<template>
  <view class="add-event-container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else>
      <view class="header">
        <text class="title">{{ isEditMode ? '编辑事件' : '创建新事件' }}</text>
      </view>

      <view class="form-container">
      <view class="form-item">
        <text class="label">事件标题 *</text>
        <input 
          class="input" 
          v-model="eventData.title" 
          placeholder="请输入事件标题"
          maxlength="30"
        />
      </view>

      <view class="form-item">
        <text class="label">事件描述</text>
        <textarea 
          class="textarea" 
          v-model="eventData.description" 
          placeholder="描述一下这个事件（可选）"
          maxlength="200"
        />
      </view>

      <view class="form-item">
        <text class="label">事件类型</text>
        <picker 
          :range="eventTypes" 
          :range-key="'label'"
          :value="selectedTypeIndex"
          @change="onEventTypeChange"
        >
          <view class="picker-display">
            <text>{{ eventTypes[selectedTypeIndex].label }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">日期 *</text>
        <picker 
          mode="date" 
          :value="eventData.eventDate"
          @change="onDateChange"
        >
          <view class="picker-display">
            <text>{{ eventData.eventDate || '请选择日期' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>

      <!-- 非全天事件才显示时间选择器 -->
      <view v-if="!eventData.isAllDay" class="form-item">
        <text class="label">开始时间</text>
        <picker 
          mode="time" 
          :value="eventData.startTime"
          @change="onStartTimeChange"
        >
          <view class="picker-display">
            <text>{{ eventData.startTime || '请选择时间' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>

      <view v-if="!eventData.isAllDay" class="form-item">
        <text class="label">结束时间</text>
        <picker 
          mode="time" 
          :value="eventData.endTime"
          @change="onEndTimeChange"
        >
          <view class="picker-display">
            <text>{{ eventData.endTime || '请选择时间' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">地点</text>
        <input 
          class="input" 
          v-model="eventData.location" 
          placeholder="事件地点（可选）"
          maxlength="50"
        />
      </view>

      <view class="form-item">
        <text class="label">提醒时间</text>
        <picker 
          :range="reminderOptions" 
          :range-key="'label'"
          :value="selectedReminderIndex"
          @change="onReminderChange"
        >
          <view class="picker-display">
            <text>{{ reminderOptions[selectedReminderIndex].label }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>

      <view class="form-item">
        <view class="switch-item">
          <text class="label">全天事件</text>
          <switch 
            :checked="eventData.isAllDay" 
            @change="onAllDayChange"
            color="#007AFF"
          />
        </view>
      </view>
    </view>

    <view class="action-buttons">
      <button class="cancel-btn" @click="goBack">取消</button>
      <button 
        class="create-btn" 
        @click="handleCreate"
        :disabled="!canCreate || creating"
      >
        {{ creating ? (isEditMode ? '保存中...' : '创建中...') : (isEditMode ? '保存事件' : '创建事件') }}
      </button>
    </view>
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'AddEvent',
  data() {
    return {
      eventData: {
        title: '',
        description: '',
        eventType: 'other',
        eventDate: '',
        startTime: '',
        endTime: '',
        location: '',
        reminderMinutes: 15,
        isAllDay: false
      },
      selectedTypeIndex: 0,
      selectedReminderIndex: 1,
      creating: false,
      isEditMode: false,
      eventId: null,
      loading: false,
      eventTypes: [
        { value: 'other', label: '其他' },
        { value: 'birthday', label: '生日' },
        { value: 'anniversary', label: '纪念日' },
        { value: 'holiday', label: '节日' },
        { value: 'meeting', label: '聚会' }
      ],
      reminderOptions: [
        { value: 0, label: '不提醒' },
        { value: 15, label: '提前15分钟' },
        { value: 30, label: '提前30分钟' },
        { value: 60, label: '提前1小时' },
        { value: 120, label: '提前2小时' },
        { value: 1440, label: '提前1天' }
      ]
    }
  },
  computed: {
    canCreate() {
      return this.eventData.title.trim() && this.eventData.eventDate
    }
  },
  async onLoad(options) {
    // 检查是否是编辑模式
    if (options.id && options.mode === 'edit') {
      this.isEditMode = true
      this.eventId = options.id
      await this.loadEventForEdit()
    } else {
      // 创建模式：如果传入了日期参数，预设日期
      if (options.date) {
        this.eventData.eventDate = options.date
      } else {
        // 默认设置为今天
        const today = new Date()
        this.eventData.eventDate = today.toISOString().split('T')[0]
      }
    }

    // 动态设置页面标题
    uni.setNavigationBarTitle({
      title: this.isEditMode ? '编辑事件' : '添加事件'
    })
  },
  methods: {
    ...mapActions('calendar', ['createEvent', 'getEventDetail', 'updateEvent']),

    async loadEventForEdit() {
      try {
        this.loading = true
        console.log('Loading event for edit, ID:', this.eventId)
        
        const eventData = await this.getEventDetail(this.eventId)
        console.log('Loaded event data:', eventData)
        
        // 填充表单数据
        this.eventData = {
          title: eventData.title || '',
          description: eventData.description || '',
          eventType: eventData.eventType || 'other',
          eventDate: eventData.eventDate || '',
          startTime: eventData.startTime || '',
          endTime: eventData.endTime || '',
          location: eventData.location || '',
          reminderMinutes: eventData.reminderMinutes || 15,
          isAllDay: eventData.isAllDay || false
        }
        
        // 设置选择器的索引
        this.selectedTypeIndex = this.eventTypes.findIndex(type => type.value === this.eventData.eventType)
        if (this.selectedTypeIndex === -1) this.selectedTypeIndex = 0
        
        this.selectedReminderIndex = this.reminderOptions.findIndex(option => option.value === this.eventData.reminderMinutes)
        if (this.selectedReminderIndex === -1) this.selectedReminderIndex = 1
        
      } catch (error) {
        console.error('加载事件数据失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        // 加载失败时返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } finally {
        this.loading = false
      }
    },

    onEventTypeChange(e) {
      this.selectedTypeIndex = e.detail.value
      this.eventData.eventType = this.eventTypes[this.selectedTypeIndex].value
    },

    onDateChange(e) {
      this.eventData.eventDate = e.detail.value
    },

    onStartTimeChange(e) {
      this.eventData.startTime = e.detail.value
    },

    onEndTimeChange(e) {
      this.eventData.endTime = e.detail.value
      
      // 验证结束时间不能早于开始时间
      if (this.eventData.startTime && this.eventData.endTime) {
        if (this.eventData.endTime <= this.eventData.startTime) {
          uni.showToast({
            title: '结束时间不能早于开始时间',
            icon: 'none'
          })
          this.eventData.endTime = ''
        }
      }
    },

    onReminderChange(e) {
      this.selectedReminderIndex = e.detail.value
      this.eventData.reminderMinutes = this.reminderOptions[this.selectedReminderIndex].value
    },

    onAllDayChange(e) {
      this.eventData.isAllDay = e.detail.value
      if (this.eventData.isAllDay) {
        // 全天事件清空时间
        this.eventData.startTime = ''
        this.eventData.endTime = ''
      }
    },

    async handleCreate() {
      if (!this.canCreate) {
        uni.showToast({
          title: '请填写必填信息',
          icon: 'none'
        })
        return
      }

      try {
        this.creating = true
        
        // 构建事件数据
        const eventPayload = {
          title: this.eventData.title,
          description: this.eventData.description,
          eventType: this.eventData.eventType,
          eventDate: this.eventData.eventDate, // 保持为日期格式 YYYY-MM-DD
          startTime: this.eventData.isAllDay ? null : this.eventData.startTime, // HH:mm 格式
          endTime: this.eventData.isAllDay ? null : this.eventData.endTime, // HH:mm 格式
          location: this.eventData.location || null,
          isAllDay: this.eventData.isAllDay
        }

        console.log('发送事件数据:', eventPayload)
        
        if (this.isEditMode) {
          // 编辑模式：更新事件
          await this.updateEvent({
            eventId: this.eventId,
            eventData: eventPayload
          })
          
          uni.showToast({
            title: '更新成功',
            icon: 'success'
          })
        } else {
          // 创建模式：创建新事件
          await this.createEvent(eventPayload)
          
          uni.showToast({
            title: '创建成功',
            icon: 'success'
          })
        }
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error(this.isEditMode ? '更新事件失败:' : '创建事件失败:', error)
        uni.showToast({
          title: this.isEditMode ? '更新失败' : '创建失败',
          icon: 'none'
        })
      } finally {
        this.creating = false
      }
    },

    buildEventDateTime() {
      const date = this.eventData.eventDate
      if (this.eventData.isAllDay || !this.eventData.startTime) {
        return date + 'T00:00:00'
      }
      return date + 'T' + this.eventData.startTime + ':00'
    },

    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.add-event-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 40rpx;
}

.header {
  margin-bottom: 40rpx;
  
  .title {
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
  }
}

.form-container {
  background: white;
  border-radius: 16rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 16rpx;
}

.input, .textarea {
  width: 100%;
  height: 100rpx;
  padding: 24rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 30rpx;
  background: #f9f9f9;
  box-sizing: border-box;
  
  &:focus {
    border-color: #007AFF;
    background: white;
  }
}

.textarea {
  min-height: 120rpx;
  resize: none;
}

.picker-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  background: #f9f9f9;
  font-size: 30rpx;
  color: #333;
  
  &:active {
    background: #f0f0f0;
  }
}

.picker-arrow {
  color: #999;
  font-size: 24rpx;
}

.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .label {
    margin-bottom: 0;
  }
}

.action-buttons {
  display: flex;
  gap: 20rpx;
}

.cancel-btn, .create-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 24rpx;
  font-size: 32rpx;
  border: none;
}

.cancel-btn {
  background: #f0f0f0;
  color: #666;
}

.create-btn {
  background: #007AFF;
  color: white;
  
  &:disabled {
    background: #ccc;
  }
}

// 加载状态
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  
  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid #e1e1e1;
    border-top: 4rpx solid #007AFF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #666;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 